package com.demo.tcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.nio.Buffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @author gy
 * @date 2022/7/31
 */
public class MyClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private int count;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("MyClientHandler 发送数据");
        // 使用客户端发送10条数据 hello,server 编号
        for (int i = 0; i < 10; i++) {
            ByteBuf byteBuf = Unpooled.copiedBuffer("hello,server " + i, StandardCharsets.UTF_8);
            ctx.writeAndFlush(byteBuf);
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {

        // 客户端 业务处理handler 在收到服务端发送过来的数据时进行处理
        byte[] responseBuffer = new byte[msg.readableBytes()];
        msg.readBytes(responseBuffer);

        String messageServer = new String(responseBuffer, StandardCharsets.UTF_8);
        System.out.println("客户端接收到消息 = " + messageServer);
        System.out.println("客户端接收消息数量 = " + (++this.count));
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
